/*
 *  Copyright (C) 2010 Francesco Boffa (aka AlfaOmega08)
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package Engine;

import ImageFormats.*;
import java.util.*;
import java.util.regex.*;

public class SystemCnf {
	ImageFormat Image;
	Hashtable<String, String> SystemConfiguration = new Hashtable();

	public void LoadFromImage(ImageFormat p) throws Exception {
		Image = p;

		ReadSystemCnf();
	}

	private void ReadSystemCnf() throws Exception {
		String[] SysCnfLines = getSysCnfLines();

		Pattern Regex = Pattern.compile("([A-Z]+)\\s*=\\s*(.+)");
		for (int i = 0; i < SysCnfLines.length; i++) {
			Matcher matcher = Regex.matcher(SysCnfLines[i]);
			Boolean found = matcher.find();
			if (!found) {
				throw new Exception("The System.cnf file is invalid");
			}
			SystemConfiguration.put(matcher.group(1), matcher.group(2));
		}
	}

	private String[] getSysCnfLines() throws Exception {
		TreeElement syscnfinfo = Image.getNodeInfo("/SYSTEM.CNF");
		byte[] syscnf = Image.getFileContent(syscnfinfo);
		String[] SysCnfLines = new String(syscnf, 0, syscnfinfo.getSize()).split("\n");

		for (int i = 0; i < SysCnfLines.length; i++) {
			SysCnfLines[i].trim();
		}

		return SysCnfLines;
	}

	public String getExecutablePath() throws Exception {
		String tmp = SystemConfiguration.get("BOOT");
		tmp = tmp != null ? tmp : "cdrom:\\PSX.EXE;1";

		Pattern Regex = Pattern.compile("cdrom:\\\\+(.*);1");
		Matcher matcher = Regex.matcher(tmp);

		if (!matcher.find()) {
			throw new Exception("Invalid system.cnf. Was matching: " + tmp);
		}

		return new String("/" + matcher.group(1).replace("\\", "/"));
	}

	public long getStackPointer() {
		String tmp = SystemConfiguration.get("STACK");
		tmp = tmp != null ? tmp : "801FFF00";

		long val = Long.parseLong(tmp, 16);
		return val;
	}

	public String getSetting(String name)
	{
		String ret = SystemConfiguration.get(name);
		return ret != null ? ret : "";
	}
}
